from django.shortcuts import render, redirect

# Create your views here.
from django.views import View
from publish.models import Publish


def publish_detail(request):
    publish_date = Publish.objects.all()
    if request.method == "POST":
        publish_id = request.POST.get("author_id") or request.POST.get("id")
        action = request.POST.get("action")
        publish_obj = Publish.objects.get(pk=publish_id)
        if action == 'update':
            data = request.POST
            publish_obj.name = data.get('name')
            publish_obj.addr = data.get('addr')
            publish_obj.email = data.get('email')
            publish_obj.save()
        if action == 'del':
            publish_obj.delete()

    return render(request, 'publish_detail.html', locals())


class Publish_add(View):
    def get(self, request, *args, **kwargs):
        return render(request, 'publish_add.html', locals())

    def post(self, request, *args, **kwargs):
        publish_obj = Publish.objects.all()
        name_list = [data.name for data in publish_obj]
        print(name_list)
        data = request.POST
        print(data)
        name = data.get('name')
        addr = data.get('addr')
        email = data.get('email')
        if name not in name_list:
            Publish.objects.create(name=name, addr=addr, email=email)

        return redirect('publish_detail')
